﻿using System;
using System.Linq;
using Eric.SerialPorts;
using SerialPortWrappers.Test.Services;

namespace SerialPortWrappers.Test.Client
{
    internal class ClientEnd
    {
        private readonly SerialPortWrapper _serialPort;

        public ClientEnd()
        {
            _serialPort = new SerialPortWrapper(new SerialPortParameter("COM1"), new TestDataVerifier());
            _serialPort.BizCommandReceivedEvent += SerialPortBizCommandReceivedEvent;
            _serialPort.ErrorReceived += _serialPort_ErrorReceived;
        }

        void _serialPort_ErrorReceived(object sender, System.IO.Ports.SerialErrorReceivedEventArgs e)
        {
            Console.WriteLine("Error occured, type is: " + e.EventType + ".");
        }

        void SerialPortBizCommandReceivedEvent(object sender, SerialPortWrapperDataEventArgs e)
        {
            if (e.Bytes == null || e.Bytes.Count() != 3)
                return;
            if (e.Bytes[0] == (byte)CommandType.Add)
            {
                var sum = BitConverter.ToUInt16(new byte[] { e.Bytes[1], e.Bytes[2] }, 0);
                Console.WriteLine("The sum of 2 and 1 is:" + sum + ".");

                System.Threading.Thread.Sleep(1000); //Sleep for better monitoring.
                _serialPort.Send(new byte[] { (byte)CommandType.Reduce, 2, 1 });
            }
            else if (e.Bytes[0] == (byte)CommandType.Reduce)
            {
                var diff = BitConverter.ToUInt16(new byte[] { e.Bytes[1], e.Bytes[2] }, 0);
                Console.WriteLine("The difference of 2 and 1 is:" + diff + ".");
            }
        }

        public void Start()
        {
            _serialPort.Open();

            if (_serialPort == null || !_serialPort.IsOpen)
            {
                Console.WriteLine("Serial port is not started yet, can't continue.");
                return;
            }

            System.Threading.Thread.Sleep(1000); //Sleep for better monitoring.
            _serialPort.Send(new byte[] { (byte)CommandType.Add, 2, 1 });
        }
    }
}
